package chaoyue.study.juc;

import chaoyue.study.ThreadUtils;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 可以理解为能够循环使用的CountDownLatch
 */
public class CyclicBarrierTest {
    public static void main(String[] args) throws InterruptedException {
        // 所有的task执行结束后 这个线程才会被执行
        Runnable other = () -> System.out.println("all tasks end, other start!");
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3, other);

        for (int i = 1; i <= 3; i++) {
            int count = i;
            new Thread(() -> {
                try {
                    ThreadUtils.sleepRandom();
                    System.out.println("task" + count + " end");
                    cyclicBarrier.await(); // await表示当前任务已经结束
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }

        //Thread.sleep(5000);

        // reset可以重置CyclicBarrier，达到复用的效果
        cyclicBarrier.reset();
        System.out.println("-------------reset-----------");
    }
}
